package com.example.dormitorysystem.common.jwt;

import com.auth0.jwt.interfaces.Claim;
import com.example.dormitorysystem.exception.CmsException;
import com.example.dormitorysystem.exception.ErrorCode;
import com.example.dormitorysystem.utils.RedisUtil;
import com.example.dormitorysystem.utils.Response;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * JWT过滤器，拦截指定的请求
 */
@Slf4j
@WebFilter(filterName = "JwtFilter", urlPatterns = {
        "/order/*",
        "/team/create",
        "/team/del",
        "/user/*",
        "/team/join",
        "/team/quit",
        "/team/my",
        "/auth/logout",
        "/team/transfer"
})
public class JwtFilter implements Filter {
    @Resource
    private RedisUtil redisUtil;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        final HttpServletRequest request = (HttpServletRequest) req;
        final HttpServletResponse response = (HttpServletResponse) res;
        response.setCharacterEncoding("UTF-8");

        String token = request.getHeader("Authorization");
        Map<String, Object> map = new HashMap<>();
        if (token == null) {
            map.put("code", 400);
            map.put("message", "尚未登录！");
            String json = new ObjectMapper().writeValueAsString(map);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().println(json);
            return;
        }
        token = token.substring("Bearer ".length());
        System.out.println(token);

        if ("OPTIONS".equals(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            chain.doFilter(request, response);
        } else {


            Map<String, Claim> userData = JwtUtil.verifyToken(token);
            if (userData == null) {
                map.put("code", 401);
                map.put("message", "当前token已过期，请刷新token！");
                String json = new ObjectMapper().writeValueAsString(map);
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().println(json);
                return;
            }

            String uid = userData.get("uid").asString();
            String userName = userData.get("username").asString();
            String password = userData.get("password").asString();
            if (redisUtil.get("TOKEN_" + uid) == null) {
                map.put("code", 400);
                map.put("message", "token已过期");
                String json = new ObjectMapper().writeValueAsString(map);
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().println(json);
                return;
            }
            ////把用户 ID 放到 MDC 上下文中
            //MDC.put("uid", uid);

            System.out.println(uid);
            System.out.println(userName);
            System.out.println(password);

            //SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

            System.out.println(userData.get("expireDate").asString());

            System.out.println("过期时间:" + userData.get("expireDate").asString());
            System.out.println("当前时间:" + new Date());

            // 拦截器 拿到用户信息，放到request中
            request.setAttribute("uid", uid);
            request.setAttribute("username", userName);
            request.setAttribute("password", password);
            chain.doFilter(req, res);
        }
    }

    @Override
    public void destroy() {
    }
}